<?php
// 应用公共文件
use tool\Auth;
use PHPMailer\PHPMailer;

//统一返回信息
function msg($code, $data, $msg)
{
    return compact('code', 'data', 'msg');
}

/*
 * 判断是否整数或浮点数做四舍五入并保留2位浮点数，不够以0充数
 */
if (! function_exists('get_numeric')) {

    function get_numeric($val)
    {
        if (is_numeric($val)) {
            return sprintf("%.2f", $val + 0);
        }
        return 0;
    }
}

/*
 * 过滤字符串中只能有中文字母数字和小点-
 */
if (! function_exists('filterOrders')) {

    function filterOrders($val)
    {
        preg_match_all('/[\x{4e00}-\x{9fa5}a-zA-Z0-9.-]/u', $val, $item);
        return join('', $item[0]);
    }
}

/*
 * 过滤字符串中只能有数字和小点
 */
function filter_mount($val)
{
    preg_match_all('/[0-9.]/u', $val, $item);
    return join('', $item[0]);
}

/*
 * 过滤字符串中只能有数字
 */
function filter_numbers($val)
{
    preg_match_all('/[0-9]/u', $val, $item);
    return join('', $item[0]);
}

/*
 * 判断是否0以上数字
 * 可带引号判断
 * 带小数点为false
 *
 */
function isInteger($input)
{
    return (ctype_digit(strval($input)));
}

/*
 * 随机数
 */
if (! function_exists('NoRand')) {

    function NoRand($begin = 1, $end = 9, $limit = 4)
    {
        $rand_array = range($begin, $end);
        shuffle($rand_array); // 调用现成的数组随机排列函数
        return array_slice($rand_array, 0, $limit); // 截取前$limit个
    }
}

// 随机字符串
function GetRandStr($length = 8)
{
    $chars = array(
        'a',
        'b',
        'c',
        'd',
        'e',
        'f',
        'g',
        'h',
        'i',
        'j',
        'k',
        'l',
        'm',
        'n',
        'o',
        'p',
        'q',
        'r',
        's',
        't',
        'u',
        'v',
        'w',
        'x',
        'y',
        'z',
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'I',
        'J',
        'K',
        'L',
        'M',
        'N',
        'O',
        'P',
        'Q',
        'R',
        'S',
        'T',
        'U',
        'V',
        'W',
        'X',
        'Y',
        'Z',
        '0',
        '1',
        '2',
        '3',
        '4',
        '5',
        '6',
        '7',
        '8',
        '9'
    );
    
    $keys = array_rand($chars, $length);
    $password = '';
    for ($i = 0; $i < $length; $i ++) {
        
        $password .= $chars[$keys[$i]];
    }
    return $password;
}

/*
 *
 * @function sendEmail
 *
 * @intro 发送邮件（带附件）
 *
 * @param $email 接收邮箱
 *
 * @param $title 邮件标题
 *
 * @param $from_name 发件人
 *
 * @param $content 邮件内容
 *
 * @param $attachmentFile 附件
 * （string | array）
 *
 * @return array
 *
 *
 */
function sendEmail($email = '', $title = '', $from_name = '', $content = '', $attachmentFile = '')
{
    date_default_timezone_set('PRC');
    
    $mail = new PHPMailer();
    
    $mail->isSMTP();
    
    $mail->SMTPDebug = 0;
    
    $mail->Debugoutput = 'html';
    
    $mail->CharSet = 'UTF-8';
    
    $mail->Host = "smtp.163.com"; // 请填写你的邮箱服务器
    $mail->SMTPSecure = 'ssl';
    $mail->Port = 465; // 端口号
    
    $mail->SMTPAuth = true;
    
    $mail->Username = "a641680308@163.com"; // 发件邮箱用户名
    
    $mail->Password = "IZVHKHHWHUOUXSZO"; // 发件邮箱密码
    
    $mail->setFrom('a641680308@163.com', $from_name);
    
    $mail->addReplyTo('a641680308@163.com', $from_name);
    
    $mail->addAddress($email);
    
    $mail->Subject = $title;
    
    $mail->msgHTML($content);
    
    $mail->AltBody = '';
    
    if (is_array($attachmentFile)) {
        
        for ($i = 0; $i < count($attachmentFile); $i ++) {
            
            $mail->addAttachment($attachmentFile[$i], 'Filename' . $i); // 这里可以是多维数组，然后循环附件的文件和名称
        }
    } else {
        
        if ($attachmentFile != '') {
            
            // Attach an image file
            
            $mail->addAttachment($attachmentFile, 'Filename');
        }
    }
    
    // send the message, check for errors
    
    if (! $mail->send()) {
        
        $status = 0;
        
        $data = "邮件发送失败" . $mail->ErrorInfo;
        ;
    } else {
        
        $status = 1;
        
        $data = "邮件发送成功";
    }
    
    return [
        'status' => $status,
        'data' => $data
    ]; // 返回值（可选）
}

function jsonTostr($data)
{
    $str = '';
    if (empty($data)) {
        return;
    }
    $json = json_decode($data);
    foreach ($json as $key => $vo) {
        $str .= $vo . '<br>';
    }
    return $str;
}

function isInString($haystack, $needle)
{
    $array = explode($needle, $haystack);
    return count($array) > 1;
}

/*
 * 字符串截取，支持中文和其他编码
 * static
 * access public
 *
 * @param string $str
 * 需要转换的字符串
 * @param string $start
 * 开始位置
 * @param string $length
 * 截取长度
 * @param string $charset
 * 编码格式
 * @param string $suffix
 * 截断显示字符
 * return string
 */
function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true)
{
    $str = strip_tags($str);
    if (function_exists("mb_substr"))
        $slice = mb_substr($str, $start, $length, $charset);
    elseif (function_exists('iconv_substr')) {
        $slice = iconv_substr($str, $start, $length, $charset);
        if (false === $slice) {
            $slice = '';
        }
    } else {
        $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("", array_slice($match[0], $start, $length));
    }
    return $suffix ? $slice: $slice;
}

// 获取模板目录
function getTem()
{
    return config('setconfig.sys_template');
}

/*
 * 生产密码
 * @param $password
 * @return string
 */
function makePassword($password)
{
    return md5($password . config('admin.salt'));
}

/*
 * 检测密码
 * @param $dbPassword
 * @param $inPassword
 * @return bool
 */
function checkPassword($inPassword, $dbPassword)
{
    return (makePassword($inPassword) == $dbPassword);
}

/*
 * 获取mysql 版本
 * @return string
 */
function getMysqlVersion()
{
    $conn = mysqli_connect(config('database.hostname') . ":" . config('database.hostport'), config('database.username'), config('database.password'), config('database.database'));
    
    return mysqli_get_server_info($conn);
}

/*
 * 生成layui子孙树
 * @param $data
 * @return array
 */
function makeTree($data)
{
    $res = [];
    $tree = [];
    
    // 整理数组
    foreach ($data as $key => $vo) {
        $res[$vo['id']] = $vo;
        $res[$vo['id']]['children'] = [];
    }
    unset($data);
    
    // 查询子孙
    foreach ($res as $key => $vo) {
        if ($vo['pid'] != 0) {
            $res[$vo['pid']]['children'][] = &$res[$key];
        }
    }
    
    // 去除杂质
    foreach ($res as $key => $vo) {
        if ($vo['pid'] == 0) {
            $tree[] = $vo;
        }
    }
    unset($res);
    
    return $tree;
}

 

/*
 * 标准返回
 * @param $code
 * @param $data
 * @param $msg
 * @return \think\response\Json
 */
function reMsg($code, $data, $msg, $count = '0')
{
    return json([
        'code' => $code,
        'data' => $data,
        'msg' => $msg,
        'count' => $count
    ]);
}

/*
 * model返回标准函数
 * @param $code
 * @param $data
 * @param $msg
 * @return array
 */
function modelReMsg($code, $data, $msg)
{
    return [
        'code' => $code,
        'data' => $data,
        'msg' => $msg
    ];
}

 /**
  * 根据ip定位
  * @param $ip
  * @return string
  * @throws Exception
  */
 function getLocationByIp($ip)
 {
     $ip2region = new \Ip2Region();
     $info = $ip2region->btreeSearch($ip);
 
     $info = explode('|', $info['region']);
 
     $address = '';
     foreach($info as $vo) {
         if('0' !== $vo) {
             $address .= $vo . '-';
         }
     }
 
     return rtrim($address, '-');
 }
 
